﻿using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using MD5Hash;
using MediatR;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json.Linq;
using ProduceBasicData.Api.Application.Command.User;
using ProduceBasicData.Api.DTO;
using ProduceBasicData.Domain.RBAC;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;

namespace ProduceBasicData.Api.Application.Handler.User
{
    /// <summary>
    /// 登录处理类
    /// </summary>
    public class LoginUserHandler : IRequestHandler<LoginUserCommand, ApiResult<UserDto>>
    {
        private readonly IBaseRespository<UserModel> userRepo;
        private readonly IBaseRespository<RoleModel> roleRepo;
        private readonly IBaseRespository<UserRoleModel> userroleRepo;
        private readonly ILogger<LoginUserHandler> logger;
        private readonly IConfiguration configuration;

        public LoginUserHandler(IBaseRespository<UserModel> userRepo,
            IBaseRespository<RoleModel> roleRepo,
            IBaseRespository<UserRoleModel> userroleRepo,ILogger<LoginUserHandler> logger,
            IConfiguration configuration)
        {
            this.userRepo = userRepo;
            this.roleRepo = roleRepo;
            this.userroleRepo = userroleRepo;
            this.logger = logger;
            this.configuration = configuration;
        }

        public async Task<ApiResult<UserDto>> Handle(LoginUserCommand request, CancellationToken cancellationToken)
        {
            ApiResult<UserDto> res=new ApiResult<UserDto>();
            var user = userRepo.GetAll().Where(x=>x.UserName==request.UserName).FirstOrDefault();
            if (user == null)
            {
                res.Code=ApiEnum.Failed;
                res.Msg = "用户名不存在";
                return res;
            }

            var pwd = request.UserPwd.GetMD5();
            if (pwd!= user.UserPwd)
            {
                res.Code = ApiEnum.Failed;
                res.Msg = "用户名密码不匹配";
                return res;
            }

            var userrole = userroleRepo.GetAll().Where(x=>x.UserId==user.Id).FirstOrDefault();
            if (userrole== null)
            {
                res.Code = ApiEnum.Failed;
                res.Msg = "请联系管理员为您配置角色";
                return res;
            }

            var role = await roleRepo.GetModelAsync(userrole.RoleId);
            if (role==null)
            {
                res.Code = ApiEnum.Failed;
                res.Msg = "请联系管理员为您分配角色";
                return res;
            }

            UserDto userDto = new UserDto()
            {
                UserName = user.UserName,
                Name = user.Name,
                UserId= user.Id,
                RoleName=role.RoleName,
                
            };
            userDto.JwtToken = CreateTokenString(userDto);
            res.Data = userDto;
            res.Code=ApiEnum.Success;
            res.Msg = "登录成功";
            return res;
        }

        /// <summary>/// 生成 JWT Token（令牌）/// </summary>/// <returns></returns>
        private string CreateTokenString<T>(T dto)
        {

            //私钥
            var secretByte = Encoding.UTF8.GetBytes(configuration["JwtConfiguration:SecretKey"]);
            // 非对称加密
            var signingKey = new SymmetricSecurityKey(secretByte);
            // 使用256 生成数字签名
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
            
            var claims=new List<Claim>();
            var type=typeof(T);
            foreach (var item in type.GetProperties())
            {
                var name=item.Name;
                var values=item.GetValue(dto);
                Claim claim = new Claim(name, values?.ToString()??"");
                claims.Add(claim);
            }
            // 生成Token
            var token = new JwtSecurityToken(
                issuer: configuration["JwtConfiguration:Issuer"],
                audience: configuration["JwtConfiguration:Audience"],
                claims: claims,
                expires: DateTime.Now.AddDays(1), // 一天后过期
                signingCredentials: signingCredentials
            );
            // 生成token 字符串
            var strToken = new JwtSecurityTokenHandler().WriteToken(token);
            return strToken;
        }
    }
}
